<template>
  <transition-group class="file-list" name="el-fade-in-linear" tag="div">
    <div class="file-list__item" v-for="(file, index) in fileLists" :key="index">
      <div class="el-icon-document name" :title="file.fileName">{{ file.name ?? file.fileName }}</div>
      <el-link v-if="file.previewUrl" type="success" :underline="false" @click="handlePreview(file)">预览</el-link>
      <el-link v-if="props.downloadUrl" type="primary" :underline="false" @click="handleDownload(file)">下载</el-link>
      <el-link type="danger" :underline="false" @click="handleDelete(index)" v-if="showDelete">删除</el-link>
    </div>
  </transition-group>
</template>
<script setup lang="ts">
import { ComponentInternalInstance, PropType } from 'vue';
import { FileListProps } from './types';
const emits = defineEmits(['upLoadFile']);
const props = defineProps({
  fileLists: {
    type: Array as PropType<FileListProps[]>,
    defalut: () => []
  },
  showDelete: {
    type: Boolean,
    default: false
  },
  downloadUrl: {
    type: String,
    default: '/common/downloadFile'
  }
});
let { fileLists } = toRefs(props);

/** 预览文件 */
const handlePreview = async (row: FileListProps) => {
  // filePreviewRef.value?.init(row);
  window.open(`${import.meta.env.VITE_PREVIEW}?url=` + encodeURIComponent(btoa(row.previewUrl as string)));
};

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;
/** 下载文件 */
const handleDownload = (row: FileListProps) => {
  proxy?.download(props.downloadUrl, {
    fileName: row.serverFileName,
    bucketName: row.bucketName,
  }, row.fileName, 'get');
};

/** 删除文件 */
const handleDelete = (index: number) => {
  fileLists?.value?.splice(index, 1);
  emits('upLoadFile');
};
</script>
<style scoped lang="scss">
.file-list {
  min-width: 200px;
  width: auto;

  &__item {
    display: flex;
    align-items: center;
    height: 30px;
    line-height: 30px;
    padding: 0 6px;

    &:hover {
      background-color: #f8f8f8;
    }

    .name {
      flex: 1;
      margin-right: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .el-link:not(:last-child) {
      margin-right: 6px;
    }
  }
}
</style>
